rm(list=setdiff(ls(), "twd")) 
library(terra)
options(warn=-1)


prec_vote<-read.csv(file=paste(twd,"data/GIS/Davidson County Precincts 2020.csv",sep=""))


prec_vote$vote_totals<-apply(prec_vote[,12:27],1,sum,na.rm=T)
prec_vote$treated<-prec_vote$Polling.Place.Change..1...Yes..0...No.
prec_vote$overflow<-ifelse(prec_vote$Location %in% prec_vote$New.Location.Name,1,0 )
prec_vote$control<-ifelse(prec_vote$treated == 0 & prec_vote$overflow==0,1,0)
prec_vote$status<-ifelse(prec_vote$treated==1, "Precinct Moved", "Control")
prec_vote$status<-ifelse(prec_vote$overflow==1, "Overflow", prec_vote$status)
prec_vote_shares<-prec_vote[,12:27]/prec_vote$vote_totals
prec_vote_shares<-data.frame(prec_vote[,1:11], prec_vote_shares)
prec_vote_shares$overflow<-ifelse(prec_vote_shares$Location %in% prec_vote_shares$New.Location.Name,1,0 )
prec_vote_shares$treated<-prec_vote_shares$Polling.Place.Change..1...Yes..0...No.
non_over_flow<-prec_vote_shares[prec_vote$Location %in% prec_vote$New.Location.Name ==F,]
overflow<-prec_vote_shares[prec_vote$Location %in% prec_vote$New.Location.Name ==T,]
treated<-non_over_flow[non_over_flow$Polling.Place.Change..1...Yes..0...No.==1,]
control<-non_over_flow[non_over_flow$Polling.Place.Change..1...Yes..0...No.==0,]

treated<-treated[!is.na(treated[,12]),]
control<-control[!is.na(control[,12]),]
overflow<-overflow[!is.na(overflow[,12]),]


groups<-list(treated,control,overflow)



treated_prec<-paste(treated$Dis.,treated$Prec.,sep="-")
overflow_prec<-paste(overflow$Dis.,overflow$Prec.,sep="-")



streets<-vect(paste(twd,"data/GIS/Streets.shp",sep=""))

streets2<-project(streets, "EPSG:4326")



pdf(paste(twd,"figs/treatment_districts_plot.pdf",sep=""),6,6)

plot(streets2,col=rgb(.2,.2,.2,.05),xlim=c(-87.0,-86.6),axes=F)

prec<-vect(paste(twd,"data/GIS/2011_Precincts.shp",sep=""))

prec2<-project(prec, "EPSG:4326")


treated <- as.character(prec2$PRECINCT) %in% treated_prec
overflow <- as.character(prec2$PRECINCT) %in% overflow_prec

plot(prec2[treated,],col=rgb(.2,.2,.2,.25),add=T,border=F,axes=F)
plot(
  prec2[overflow, ],
  density = 20,
  angle = 45,
  add = TRUE,
  border = NA
)

polling_place_lat_lon<-read.csv(paste(twd,"data/made_data/polling_place_lat_lon.csv",sep=""))

points(polling_place_lat_lon$lon,polling_place_lat_lon$lat,pch=17,col="dark green",cex=.5)

dev.off()





pdf(paste(twd,"figs/damage_plot.pdf",sep=""),6,6)

plot(streets2,col=rgb(.2,.2,.2,.05),xlim=c(-87.0,-86.6),axes=F)

plot(prec2[treated,],col=rgb(.2,.2,.2,.25),add=T,border=F)
plot(
  prec2[overflow, ],
  density = 20,
  angle = 45,
  add = TRUE,
  border = NA
)


damage<-read.csv(paste(twd,"data/damage_data/Davidson_County_Tornado_Damage_data.csv",sep=""))

damages_2<-read.csv(paste(twd,"data/made_data/power_outages.csv",sep=""))

points(damages_2$lon,damages_2$lat,pch=1,col="dark blue",cex=.5)
points(damage$Longitude,damage$Latitude,pch=16,col="black",cex=.5)


dev.off()
